package cn.fl.capital.service.impl;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.comm.facade.framework.dto.SysDictionaryDTO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.Pager;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.capital.condition.CapFeeOutLogQueryCondition;
import cn.fl.capital.constant.CapitalConstant;
import cn.fl.capital.dto.CapFeeOutLogDTO;
import cn.fl.capital.service.ICapFeeOutLogApiService;
import cn.fl.capital.service.ICapFeeOutLogService;
import cn.fl.capital.transform.CapFeeOutLogVOTransform;
import cn.fl.capital.vo.CapFeeOutLogVO;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.project.condition.PrjPrdPaySchDQueryCondition;
import cn.fl.project.condition.PrjPrdPaySchMQueryCondition;
import cn.fl.project.constant.PrjPrdPaySchMConstant;
import cn.fl.project.dto.PrjPrdPaySchDDTO;
import cn.fl.project.dto.PrjPrdPaySchMDTO;
import cn.fl.project.service.IPrjPaySchDApiService;
import cn.fl.project.service.IPrjPrdPaySchMApiService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Description: 支付表费用转出记录表 客户端服务层接口实现
 * 业务层方法名称前缀：
 * 新增：add*
 * 删除：remove*
 * 修改：modify*
 * 批量：batch*
 * 查询对象：select* get*
 * 查询集合：search*
 */
@Service
public class CapFeeOutLogServiceImpl implements ICapFeeOutLogService {

	/**
     * 日志
     */
    @SuppressWarnings("unused")
    private static final Logger logger = LoggerFactory.getLogger(CapFeeOutLogServiceImpl.class);
	
	/**
	 * 支付表费用转出记录表 暴露服务
	 */
	@Autowired
	private ICapFeeOutLogApiService capFeeOutLogApiService;
	/**
     * 数据字典服务
     */
    @Autowired
    private ISysDictionaryApiService sysDictionaryApiService;

	@Autowired
	private IPrjPaySchDApiService prjPaySchDApiService;

	@Autowired
	private IPrjPrdPaySchMApiService prjPrdPaySchMApiService;



	@Override
	public CapFeeOutLogVO selectById(Long id) throws BaseException{
		if(StringUtils.isEmpty(id)) return null;
		CapFeeOutLogDTO dto = this.capFeeOutLogApiService.selectCapFeeOutLogById(id);
		return CapFeeOutLogVOTransform.toVO(dto);
	}

	@Override
	public Long add(CapFeeOutLogVO entity) throws BaseException{
		if(null == entity) return null;
		return this.capFeeOutLogApiService.addCapFeeOutLog(CapFeeOutLogVOTransform.toDTO(entity));
	}

	@Override
	public boolean removeByIds(List<Long> ids) throws BaseException{
		if(CollectionUtils.isEmpty(ids)) return false;
		return this.capFeeOutLogApiService.removeCapFeeOutLogByIds(ids,CurrentThreadContext.getCurrentUserId());
	}

	@Override
	public boolean modify(CapFeeOutLogVO entity) throws BaseException{
		if(null == entity) return false;
		return this.capFeeOutLogApiService.modifyCapFeeOutLog(CapFeeOutLogVOTransform.toDTO(entity));
	}

	@Override
	public Pager searchListPage(Pager page) throws BaseException{
        CapFeeOutLogQueryCondition condition=null;
        if(null == page) {
            page = new Pager();
            page.setCondition(new CapFeeOutLogQueryCondition());
        }
		condition=(CapFeeOutLogQueryCondition)page.getCondition();
        condition.setSysCd(CurrentThreadContext.getCurrentSysCd());//当前系统代码
        condition.setOrgCd(CurrentThreadContext.getCurrentOrgCd());//当前机构代码
        condition.setUsrId(CurrentThreadContext.getCurrentUserId());//当前用户ID
		page=this.capFeeOutLogApiService.searchCapFeeOutLogListPage(page);
		if(CollectionUtils.isNotEmpty(page.getResultList())){
            List<CapFeeOutLogVO> voList=CapFeeOutLogVOTransform.toVOList((List<CapFeeOutLogDTO>)page.getResultList());
            this.setDictData(voList);
            page.setResultList(voList);
        }
        return page;
	}
	
	@Override
	public List<CapFeeOutLogVO> searchList(CapFeeOutLogQueryCondition condition) throws BaseException{
		if(null == condition) condition=new CapFeeOutLogQueryCondition();
		condition.setSysCd(CurrentThreadContext.getCurrentSysCd());//当前系统代码
		condition.setOrgCd(CurrentThreadContext.getCurrentOrgCd());//当前机构代码
		condition.setUsrId(CurrentThreadContext.getCurrentUserId());//当前用户ID
		List<CapFeeOutLogVO> voList=CapFeeOutLogVOTransform.toVOList(this.capFeeOutLogApiService.searchCapFeeOutLogList(condition));
		this.setDictData(voList);
		return voList;
	}

	@Override
	public List<CapFeeOutLogDTO> searchListForMore(CapFeeOutLogQueryCondition condition) throws BaseException {
		if (null == condition) condition = new CapFeeOutLogQueryCondition();
		condition.setSysCd(CurrentThreadContext.getCurrentSysCd());//当前系统代码
		condition.setOrgCd(CurrentThreadContext.getCurrentOrgCd());//当前机构代码
		condition.setUsrId(CurrentThreadContext.getCurrentUserId());//当前用户ID
		return capFeeOutLogApiService.searchListForMore(condition);
	}
	
    /**
     * 添加数据字典名称
     * @param voList
     */
	public void setDictData(List<CapFeeOutLogVO> voList){
		if(CollectionUtils.isEmpty(voList)) return;
		Map<String, String> handleWayCdMap = this.sysDictionaryApiService.searchGroupToMap(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), CapitalConstant.CODE_HANDLE_WAY_CD);
		Map<String, String> feeTypCdMap = this.sysDictionaryApiService.searchGroupToMap(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), CapitalConstant.CODE_FEE_TYP_CD);

		for(CapFeeOutLogVO vo:voList){
			if (CollectionUtils.isMapNotEmpty(handleWayCdMap) && handleWayCdMap.containsKey(vo.getHandleWayCd())) {
            	vo.setHandleWayCdNm(handleWayCdMap.get(vo.getHandleWayCd()));
        	}
        	if(StringUtils.isBlank(vo.getFeeTypCdNm())&&CollectionUtils.isMapNotEmpty(feeTypCdMap)&&feeTypCdMap.containsKey(vo.getFeeTypCd())){
        		vo.setFeeTypCdNm(feeTypCdMap.get(vo.getFeeTypCd()));
			}
		}
	}
	
	/**
     * 查询数据字典
     * @param groupCd 组代码
     * @return List<KeyValueVO>
     */
    public List<KeyValueVO> searchDictListByGrpCd(String groupCd){
        return this.sysDictionaryApiService.getKvList(groupCd, CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd());
    }

	/**
	 * 查询保证金处理方式数据字典
	 * @param exclude 排除值
	 * @return
	 * @throws BaseException
	 */
	public List<KeyValueVO> searchHandleWayCdList(String exclude) throws BaseException{
		List<KeyValueVO> list=null;
		List<SysDictionaryDTO> dtoList=this.sysDictionaryApiService.searchGroup(CurrentThreadContext.getCurrentSysCd(),CurrentThreadContext.getCurrentOrgCd(), CapitalConstant.CODE_HANDLE_WAY_CD);
		if(CollectionUtils.isNotEmpty(dtoList)){
			list=new ArrayList<>(dtoList.size());
			KeyValueVO kv=null;
			for(SysDictionaryDTO dto:dtoList){
				if(exclude.equals(dto.getCode())){
					continue;
				}
				kv=new KeyValueVO();
				kv.setKey(dto.getCode());
				kv.setValue(dto.getCodeNm());
				list.add(kv);
			}
		}
    	return list;
	}

	/**
	 * 计算剩余客户保证金
	 * @param paySchId
	 * @param paySchTypCd
	 * @return
	 * @throws BaseException
	 */
	@Override
	public Long calcuCapFeeAmt(Long paySchId, String paySchTypCd) throws BaseException {
		Double feeTyp02 = 0D;
		Double totalOutAmt = 0D;
		Double resultAmt = 0D;
		if(PrjPrdPaySchMConstant.PAY_SCH_TYP_CD_WS.equals(paySchTypCd)){
			PrjPrdPaySchDQueryCondition prjPrdPaySchDQueryCondition = new PrjPrdPaySchDQueryCondition();
			prjPrdPaySchDQueryCondition.setPaySchId(paySchId);
			List<String> includeFeeTypCdList = new ArrayList<>(2);
			includeFeeTypCdList.add(CapitalConstant.CODE_FEE_TYP_CD_02);
			prjPrdPaySchDQueryCondition.setIncludeFeeTypCdList(includeFeeTypCdList);
			//查询保证金
			List<PrjPrdPaySchDDTO> prjPrdPaySchFeeDTOS = prjPaySchDApiService.searchPaySchFeeDtlList(prjPrdPaySchDQueryCondition);
			if(CollectionUtils.isNotEmpty(prjPrdPaySchFeeDTOS)){
				feeTyp02 = prjPrdPaySchFeeDTOS.get(0).getFeeAmt();
			}
			//查询保证金转出记录
			CapFeeOutLogQueryCondition capFeeOutLogQueryCondition = new CapFeeOutLogQueryCondition();
			capFeeOutLogQueryCondition.setPaySchId(paySchId);
			capFeeOutLogQueryCondition.setFeeTypCd(CapitalConstant.CODE_FEE_TYP_CD_02);
			List<CapFeeOutLogDTO> capFeeOutLogDTOS = capFeeOutLogApiService.searchCapFeeOutLogList(capFeeOutLogQueryCondition);
			if(CollectionUtils.isNotEmpty(capFeeOutLogDTOS)){
				for(CapFeeOutLogDTO capFeeOutLogDTO : capFeeOutLogDTOS){
					totalOutAmt += capFeeOutLogDTO.getOutAmt();
				}
			}

		}else{
			PrjPrdPaySchMQueryCondition prjPrdPaySchMQueryCondition = new PrjPrdPaySchMQueryCondition();
			prjPrdPaySchMQueryCondition.setId(paySchId);
			PrjPrdPaySchMDTO prjPrdPaySchMDTO = prjPrdPaySchMApiService.selectPrjPrdPaySchMById(paySchId);
			Long prjId = prjPrdPaySchMDTO.getPrjId();
			prjPrdPaySchMQueryCondition.setPrjId(prjId);
			prjPrdPaySchMQueryCondition.setId(null);
			prjPrdPaySchMQueryCondition.setPaySchTypCd(PrjPrdPaySchMConstant.PAY_SCH_TYP_CD_WS);
			List<PrjPrdPaySchMDTO> prjPrdPaySchMDTOS = prjPrdPaySchMApiService.searchPrjPrdPaySchMList(prjPrdPaySchMQueryCondition);
			if(CollectionUtils.isNotEmpty(prjPrdPaySchMDTOS)){
				List<Long> wsPaySchIdList = new ArrayList<>(prjPrdPaySchMDTOS.size());
				for(PrjPrdPaySchMDTO prjPrdPaySchMDTO1 : prjPrdPaySchMDTOS){
					wsPaySchIdList.add(prjPrdPaySchMDTO1.getId());
				}
				//查询保证金转出记录
				CapFeeOutLogQueryCondition capFeeOutLogQueryCondition = new CapFeeOutLogQueryCondition();
				capFeeOutLogQueryCondition.setPaySchIdList(wsPaySchIdList);
				capFeeOutLogQueryCondition.setFeeTypCd(CapitalConstant.CODE_FEE_TYP_CD_02);
				List<CapFeeOutLogDTO> capFeeOutLogDTOS = capFeeOutLogApiService.searchCapFeeOutLogList(capFeeOutLogQueryCondition);
				for(CapFeeOutLogDTO capFeeOutLogDTO : capFeeOutLogDTOS){
					totalOutAmt += capFeeOutLogDTO.getOutAmt().doubleValue();
				}
				PrjPrdPaySchDQueryCondition prjPrdPaySchDQueryCondition = new PrjPrdPaySchDQueryCondition();
				prjPrdPaySchDQueryCondition.setPaySchIdList(wsPaySchIdList);
				prjPrdPaySchDQueryCondition.setFeeTypCd(CapitalConstant.CODE_FEE_TYP_CD_02);
				//查询保证金,尾款 资管项目需要将多张我司支付表查询结果进行总和
				List<PrjPrdPaySchDDTO> prjPrdPaySchFeeDTOS = prjPaySchDApiService.searchPaySchFeeDtlList(prjPrdPaySchDQueryCondition);
				if (CollectionUtils.isNotEmpty(prjPrdPaySchFeeDTOS)) {
					for (PrjPrdPaySchDDTO prjPrdPaySchDDTO : prjPrdPaySchFeeDTOS) {
						feeTyp02 += prjPrdPaySchDDTO.getFeeAmt();

					}
				}

			}

		}
		resultAmt = feeTyp02 - totalOutAmt;
		return resultAmt.longValue();
	}
}
